<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Models\Blog;
use Illuminate\Support\Str;
use App\Models\Tag;


class BlogController extends Controller
{
    public function index()
    {
        $blogs = Blog::latest()->paginate(10);
        return view('blogs.index', ['blogs' => $blogs]);
    }

    public function show(Blog $blog)
    {
        $post = Blog::with('comments')->where('slug', $blog->slug)->first();
        return view('blogs.show', compact('post'));
    }

    public function search(Request $request)
    {
        $query = $request->input('search');
        $blogs = Blog::where('title', 'like', "%$query%")
            ->paginate(10);

        return view('blogs.index', compact('blogs'));
    }


    public function create()
    {
        $categories = Category::all();
        return view('blogs.create', compact("categories"));
    }


    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|max:255',
            'body' => 'required',
            'featured_image' => 'required|image'
        ]);

        $slug = Str::slug($request->title);
        $user_id = auth()->id();
        $featured_image = $request->file('featured_image');
        $path = $featured_image->store('images', 'public');


        $blog = Blog::create([
            'title' => $request->title,
            'featured_image' => $path,
            'body' => $request->body,
            'slug' => $slug,
            'user_id' => $user_id
        ]);

        $tags = explode(',', $request->tags);
        $tagIds = [];
        foreach ($tags as $tag) {
            $newTag = Tag::firstOrCreate(['name' => $tag, 'slug' => Str::slug($tag)]);
            array_push($tagIds, $newTag->id);
        }

        $blog->tags()->attach($tagIds);

        return redirect()->route('blogs.index')->with('success', 'Blog post created successfully.');
    }

    public function edit(Blog $blog)
    {
        return view('blogs.edit', compact('blog'));
    }

    public function update(Request $request, $slug)
    {
        $validatedData = $request->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

        $blog = Blog::where('slug', $slug)->first();
        if(auth()->id() != $blog->user_id) {
            return redirect()->route('blogs.index')->with('error', 'Permission denied');
        }

        $validatedData['slug'] = Str::slug($validatedData['title']);

        $blog->update($validatedData);

        return redirect()->route('blogs.index');
    }

    public function getPostsByTag($slug)
    {
        $tag = Tag::where('slug', $slug)->first();
        $blogs = $tag->blogs()->paginate(10);
        return view('blogs.index', compact('blogs'));
    }

}
